<?php
$allArticleCategory = $this->allArticleCategory;
$allSubArticleCategory = $this->allSubArticleCategory;
$articleItem = $this->articleItem;
?>



<div class="ad_title_ctn">
    <h2>Thêm bài viết</h2>
</div>

<div class="ad_content_ctn">
    <div class="pa_top_ctr_ctn">
        <a id="lnkSaveArticleTop" class="k-button k-button-icontext" >Lưu bài viết</a>&nbsp;&nbsp;&nbsp;
        <a id="lnkSaveAndNewArticleTop" class="k-button k-button-icontext" >Lưu và thêm mới</a>
    </div>

    <div class="pa_content_ctn" id="article_info_ctn">
        <table style="width: 100%" cellspacing="12px">
            <tr>
                <td class="title">Tiêu đề(*):</td>
                <td>
                    <input id="txtHeader" name="txtHeader" style="min-width:400px"
                           value="<?php if($articleItem)echo $articleItem->header ?>"
                           placeholder="Nhập tiêu đề bài viết, bắt buộc" class="k-textbox"
                           required validationMessage="Chưa nhập tiêu đề">
                    <span class="k-invalid-msg" data-for="txtHeader"></span>
                </td>
            </tr>
            <tr>
                <td class="title">Tóm tắt:</td>
                <td>
                    <textarea id="txtSumarize" name="txtSumarize" style="width:400px;" rows="3"  class="k-textbox"><?php if($articleItem)echo $articleItem->sumarize ?></textarea>

                </td>
            </tr>
            <tr>
                <td class="title">Nhóm chính</td>
                <td>
                    <select id="cboPrimaryCategory">
                        <option value="ALL">Không chọn</option>
                        <?php
                        foreach ($allArticleCategory as $aCategory) {
                            echo '  <option value="'.$aCategory->id.'">'.$aCategory->name.'</option>';
                        }

                        ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td class="title">Nhóm phụ</td>
                <td>
                    <select id="cboSubCategory" style="float: left">
                        <option value="ALL">Không chọn</option>
                        <?php

                        foreach ($allSubArticleCategory as $aCategory) {
                            echo '  <option value="'.$aCategory->id.'">'.$aCategory->name.'</option>';
                        }
                        foreach ($allArticleCategory as $aCategory) {
                            echo '  <option value="'.$aCategory->id.'">'.$aCategory->name.'</option>';
                        }

                        ?>
                    </select>
                    &nbsp;&nbsp;<div id="choseSubCategoryValue">
                    <?php
                        if($articleItem){
                            $subCategories = $articleItem->getSubCategories();
                            foreach ($subCategories as $aCat) {
                                echo "<div class='spnSubCatHolder'><input type='hidden' value='".$aCat->id."'>".$aCat->name."&nbsp;&nbsp;<span><a onclick='javascript:deleteSubCat(this)' href='javascript:void(0)'>Xóa</a></span></div>";
                            }


                        }
                    ?>
                    </div>
                    <div class="clear"></div>
                </td>
            </tr>
            <tr>
                <td class="title">Active</td>
                <td>
                    <?php
                        $checked = 'cheked';
                        if($articleItem)
                            if($articleItem->active == 1)
                                $checked = 'checked';
                            else
                                $checked = '';

                    ?>
                    <input type="checkbox" id="chkActive" <?php echo $checked ?> >
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <div >
                        <div style="float: left ; width:40%; border:1px solid #CCC; padding: 10px">
                            <div>
                                <a href="javascript:getThumbImg();" >Chọn ảnh thumb</a>
                                &nbsp;
                                <a id="btnRemoveThumbImg" href="javascript:removeThumbImg();"  >Xóa ảnh</a>
                                <div style="background: #F8F8F8; margin: 0 auto; padding: 5px">
                                    <img id = "imgThumb" style="max-width: 180px; max-height: 180px"
                                         src="<?php
                                         if($articleItem) echo $articleItem->thumbnail;
                                         ?>">
                                </div>

                            </div>
                        </div>
                        <div style="float: left;width:40%;border:1px solid #CCC; padding: 10px; margin-left: 15px">
                            <div >

                                <a href="javascript:getTopicImg();"  >Chọn ảnh chủ đề</a>
                                &nbsp;
                                <a id="btnRemoveTopicImg" href="javascript:removeTopicImg();" >Xóa ảnh</a>
                                <div style="background: #F8F8F8; margin: 0 auto; padding: 5px">
                                    <img id = "imgTopic" style="max-width: 180px; max-height: 180px"
                                         src="<?php
                                         if($articleItem) echo $articleItem->image;
                                         ?>">
                                </div>

                            </div>
                        </div>
                        <div class="clear"></div>
                    </div>
                </td>

            </tr>
            <tr>
                <td colspan="2">
                    <div>
                        <div class="head-container" style="height: 25px">
                            <div style="float: left; width: 80px; font-size: 12; font-weight: bold;">Nội dung </span>&nbsp;&nbsp;</div>
                            <img  src="/static/images/icons/edit.png" alt="Nhập nội dung" style="cursor: pointer; width:25px;" onclick="tougleEditor();">
                        </div>
                        <div class="clear"></div>
                        <div style="min-height: 250px ;border: 1px solid #CCC; background-color: #fff" id = "contentContainer"><?php if($articleItem)echo $articleItem->content ?></div>
                </td>

            </tr>

        </table>


    </div>

    <div class="pa_bottom_ctr_ctn">
        <a id="lnkSaveArticleBottom" class="k-button k-button-icontext">Lưu bài viết</a>&nbsp;&nbsp;&nbsp;
        <a id="lnkSaveAndNewArticleBottom" class="k-button k-button-icontext" >Lưu và thêm mới</a>
    </div>
</div>


<script type="text/javascript">
var validator;
var id;
<?php
if($articleItem)
    echo 'id = '.$articleItem->id.';';

?>
$(document).ready(function(){

    validator = $("#article_info_ctn").kendoValidator().data("kendoValidator");
    $("#cboPrimaryCategory").kendoComboBox({
        filter: "contains",
        suggest: true,
        index: 2,
        select: function(e) {
            dataItem = this.dataItem(e.item.index());
            value=dataItem[this.options.dataValueField];
            isExist = false;
            $('.spnSubCatHolder').each(function(){
                existVal = $(this).children('input').val();
                if(existVal == value){
                    isExist = true;
                }
            });
            if(isExist){
                alert("Đã tồn tại nhóm " + text + " trong nhóm phụ. Xóa trong nhóm phụ trước khi thay đổi nhóm chính.");
                e.preventDefault();
            }
        }
    });

    var cboPrimaryCategory = $("#cboPrimaryCategory").data("kendoComboBox");
    <?php
        if($articleItem){
            $primaryCategory = $articleItem->getPrimaryCategory();
            echo 'cboPrimaryCategory.value('.$primaryCategory->id.');';
        }

    ?>
    $("#cboSubCategory").kendoComboBox({
        filter: "contains",
        suggest: true,
        index: 2,
        change: function(e) {
            value = this.value();
            text = this.text();
            if(text.indexOf('-')!= 0){
                alert('Chọn nhóm bắt đầu bằng dấu -');
                return;
            }
            primaryCat = cboPrimaryCategory.text();
            if(text == primaryCat){
                alert('Chọn nhóm khác nhóm chính');
                return;
            }
            isExist = false
            $('.spnSubCatHolder').each(function(){
                existVal = $(this).children('input').val();
                if(existVal == value){
                    isExist = true;
                }
            });

            if(isExist) return;

            myHtml="<div class='spnSubCatHolder'><input type='hidden' value='"+value+"'>"+text+"&nbsp;&nbsp;<span><a onclick='javascript:deleteSubCat(this)' href='javascript:void(0)'>Xóa</a></span></div>";
            $('#choseSubCategoryValue').append(myHtml);

        }
    });
    var cboSubCategory = $("#cboSubCategory").data("kendoComboBox");

    $('#lnkSaveArticleBottom').click(function(){
        saveArticle(function(){
            window.location = '/admin/article';
        });
    })
    $('#lnkSaveArticleTop').click(function(){
        saveArticle(function(){
            window.location = '/admin/article';
        });
    })

    $('#lnkSaveAndNewArticleBottom').click(function(){
        saveArticle(function(){
            resetAll();
        });
    })
    $('#lnkSaveAndNewArticleTop').click(function(){
        saveArticle(function(){
            resetAll();
        });
    })

    function resetAll(){
        articleName = $('#txtHeader').val();
        $('#txtHeader').val('');
        $('#txtSumarize').val('');
//        cboPrimaryCategory.select(cboPrimaryCategory.ul.children().eq(0));
//        cboSubCategory.select(cboSubCategory.ul.children().eq(0));
        $('#choseSubCategoryValue').html('');
        $('#chkActive').attr('checked', true);
        $('#imgThumb').attr('src', '');
        $('#imgTopic').attr('src', '');
        if ( editor )
            editor.destroy();
        $("#contentContainer").html('');
        window.scrollTo(0, 0);
        $('#txtHeader').focus();

        $('#error_ctn').addClass('blue_text').html("Thêm mới bài viết '"+articleName +"' thành công!");
    }

    function saveArticle(successFunction){
        if(!validate())
            return;
        $.blockUI({ message: 'Vui lòng chờ...' });
        header = $("#txtHeader").val();
        sumarize = $("#txtSumarize").val();
        if(editor)
            content = editor.getData();
        else
            content = $("#contentContainer").html();
        thumbImage = $("#imgThumb").attr("src");
        topicImage = $("#imgTopic").attr("src");
        primaryCategory = cboPrimaryCategory.value();
        subCategories = []

        $('.spnSubCatHolder').each(function(){
            existVal = $(this).children('input').val();
            subCategories.push(existVal);
        });

        active = $('#chkActive').is(':checked')?1:0;
        $.post('/admin/article/save-article',{id:id,
                    header:header, sumarize:sumarize, content:content,
                    thumbImage:thumbImage,  topicImage:topicImage,primaryCategory:primaryCategory,
                    subCategories:subCategories, active:active
                }
                ,function(result){
                    $.unblockUI();
                    if (result.success){
                        successFunction()
//                            window.location = '/admin/article'
                    }else{
                        $('#error_ctn').removeClass('blue_text').html(result.msg);
                    }

                },'json');
    }

    function validate(){
        isValid = true;
        isValid = validator.validate();

        if(editor)
            content = editor.getData();
        else
            content = $("#contentContainer").html();

        if(!content || content == ''){
            alert("Vui lòng nhập nội dung");
            return false;
        }


        return isValid;
    }
});

function deleteSubCat(me){

    $(me).parent().parent().remove();
}


function getThumbImg(){
    try{
        var finder = new CKFinder();
        finder.basePath = '/static/js/ckfinder/';	// The path for the installation of CKFinder (default = "/ckfinder/").
        finder.selectActionFunction = setThumbFile;
        finder.popup();
    }catch(err){

    }
}

function removeThumbImg(){
    $("#imgThumb").attr("src", "" );
    $("#btnRemoveThumbImg").hide();
}


function setThumbFile( fileUrl )
{
    $("#imgThumb").attr("src", fileUrl );
    $("#btnRemoveThumbImg").show();
}

function getTopicImg(){
    try{
        var finder = new CKFinder();
        finder.basePath = '/static/js/ckfinder/';	// The path for the installation of CKFinder (default = "/ckfinder/").
        finder.selectActionFunction = setTopicFile;
        finder.popup();
    }catch(err){

    }
}

function removeTopicImg(){
    $("#imgTopic").attr("src", "" );
    $("#btnRemoveTopicImg").hide();
}


function setTopicFile( fileUrl )
{
    $("#imgTopic").attr("src",  fileUrl );
    $("#btnRemoveTopicImg").show();
}
var editor;
function tougleEditor(){
    if ( editor )
        editor.destroy();
    editor = CKEDITOR.replace( "contentContainer" ,{
        filebrowserBrowseUrl : '/static/js/ckfinder/ckfinder.html',
        filebrowserImageBrowseUrl : '/static/js/ckfinder/ckfinder.html?Type=Images',
        filebrowserFlashBrowseUrl : '/static/js/ckfinder/ckfinder.html?Type=Flash',
        filebrowserUploadUrl : '/static/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
        filebrowserImageUploadUrl : '/static/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
        filebrowserFlashUploadUrl : '/static/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash',
        customConfig : '/static/js/ckeditor/my_config.js',
        language: 'vi'
    });
}

</script>
<style type="text/css">
    .spnSubCatHolder{
        padding: 5px 15px 5px 0px;
        margin: 0px 10px;
        background-color: #c4c4c4;
        float: left;
    }
    .spnSubCatHolder a{
        /*display: none;*/
        visibility: hidden;
    }
    .spnSubCatHolder:hover a{
        visibility: visible;
        /*display: block;*/
    }

    #choseSubCategoryValue{float: left}

</style>